import {takeEvery, select, call, put, take} from 'redux-saga/effects'
import axios from 'axios'
import { message } from 'antd';

// 引入自定义操作
import { ChangeContentPageActivate, UserGetTaskSaga } from '../actions/contentpage'
import { ChangeSpinACtivate, ChangePageActivate } from '../actions/public'
import { GetUserBaseInfo } from '../actions/userinfo';
// 引入状态和常量
import { GETCONTENTPAGESAGA, USERGETTASKSAGA, USERUPDATEBASEINFOSAGA } from '../constants'
import { duration } from 'moment';
import { API_URL } from '../../env';

function* getContentPageSaga(action) {
    console.log("进入首页了，开始请求后端数据")
    const publicState = yield select(state => state.PublicReducer) 
    const page = publicState.page // 获取页数
    const search_value = publicState.search_value // 搜索关键词
    const task_type_id = publicState.task_type_id // 任务类型
    const obj = {
        page: page,
        search_value: search_value,
        task_type_id: task_type_id
    }

    const res = yield call(axios.post, API_URL + "content/get_content", {...obj}) // 请求后端获得数据
    console.log("getContentPageSaga is ", res.data)
    if (res.status == 200){
        if (Object.keys(res.data.content_data).length === 0 && page > 0 ){
            // 如果领取后，本页已经没有了，则跳回上一页
            yield put(ChangePageActivate({page: page-1}))
            window.location.reload()
        } else {
            yield put(ChangeContentPageActivate({...res.data}))
            window.scrollTo(0,-1)
            yield put(ChangeSpinACtivate({getContent_activate: false}))
        }  
    } else{
        console.log("contentSaga getContentPageSaga error is ", res)
    } 
}

function* userGetTaskSaga(action) {
    console.log("点击领取任务了，向后端记录", action.data)
    try{
        const res = yield call(axios.post, API_URL + "content/user_get_task", {...action.data})
        if (res.status == 200){
            if (res.data.status === 4003) {
                message.warning('非常抱歉，自己不能领取自己的任务')
            } else {
                // 先提示，再刷新
                message.success('领取成功', duration=0.1).then(()=>{window.location.reload()})
            }
        } else {
            message.error('领取失败')
        }
    } catch(e) {
        message.error('领取失败')
    }
    
}

// 刷新更新基本信息
function* userUpdateBaseInfoSaga(action) {
    console.log("userUpdateBaseInfoSaga is ", action.data)
    try {
        const res = yield call(axios.post, API_URL + "content/update_baseinfo", {...action.data})
        if (res.status == 200) {
            yield put(GetUserBaseInfo(res.data))
        }
    } catch(e) {

    }
}

export function* contentpageSaga () {
    yield takeEvery(GETCONTENTPAGESAGA, getContentPageSaga)
    yield takeEvery(USERGETTASKSAGA, userGetTaskSaga)
    yield takeEvery(USERUPDATEBASEINFOSAGA, userUpdateBaseInfoSaga)
}
